package errors

import (
	"fmt"
	"manage/internal/routes/middleware"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type ErrorHandler interface {
	HandleError(ctx *gin.Context, err error, msg string)
}

type StandardResponse struct {
	Code int64       `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

// MicroserviceErrorHandler 微服务异常
type MicroserviceErrorHandler struct{}

func (e *MicroserviceErrorHandler) HandleError(ctx *gin.Context, err error, msg string) {
	if err != nil {
		middleware.Log.Error("Microservice error: ", err)
	}
	ctx.JSON(http.StatusOK, &StandardResponse{
		Code: http.StatusInternalServerError,
		Msg:  msg,
		Data: "",
	})
}

// RequestErrorHandler 请求异常
type RequestErrorHandler struct{}

func (e *RequestErrorHandler) HandleError(ctx *gin.Context, err error, msg string) {
	if err != nil {
		middleware.Log.Error("Request error: ", err)
	}

	if value := strings.Split(msg, ":"); len(value) != 0 {
		msg = value[1]
	}

	ctx.JSON(http.StatusOK, &StandardResponse{
		Code: http.StatusBadRequest,
		Msg:  msg,
		Data: "",
	})
}

// DefaultErrorHandler 默认异常(网关)
type DefaultErrorHandler struct{}

func (e *DefaultErrorHandler) HandleError(ctx *gin.Context, err error, msg string) {
	if err != nil {
		middleware.Log.Error("An error occurred: ", err)
	}
	ctx.JSON(http.StatusOK, &StandardResponse{
		Code: http.StatusBadGateway,
		Msg:  "API网关异常",
		Data: "",
	})
}

// NewErrHandler 工厂方法
func NewErrHandler(errType string) ErrorHandler {
	switch errType {
	case "MicroserviceError":
		return &MicroserviceErrorHandler{}
	case "RequestError":
		return &RequestErrorHandler{}
	default:
		return &DefaultErrorHandler{}
	}
}

// errors.CheckErr 错误定义
func CheckErr(ctx *gin.Context, err error, name string, code int64, msg string) (flag bool) {
	if err != nil {
		NewErrHandler("MicroserviceError").HandleError(ctx, err, fmt.Sprintf("%s异常", name))
	} else {
		if code != 200 {
			NewErrHandler("RequestError").HandleError(ctx, err, msg)
		} else {
			flag = true
		}
	}
	return
}
